package cn.appsys.controller.backend;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.appsys.pojo.AppCategory;
import cn.appsys.pojo.AppInfo;
import cn.appsys.pojo.AppVersion;
import cn.appsys.pojo.BackendUser;
import cn.appsys.pojo.DataDictionary;
import cn.appsys.pojo.DevUser;
import cn.appsys.service.backend.BackendUser.BackendUserService;
import cn.appsys.service.developer.AppCategory.AppCategoryService;
import cn.appsys.service.developer.AppInfo.AppInfoService;
import cn.appsys.service.developer.AppVersion.AppVersionService;
import cn.appsys.service.developer.DataDictionary.DataDictionaryService;
import cn.appsys.tools.Constants;
import cn.appsys.tools.PageSupport;

@Controller
@RequestMapping("/manager")
public class BackendController {

	private Logger logger = Logger.getLogger(BackendController.class);

	@Resource
	BackendUserService backendUserService;
	@Resource
	AppInfoService appInfoService;
	@Resource
	DataDictionaryService dataDictionaryService;
	@Resource
	AppCategoryService appCategoryService;
	@Resource
	AppVersionService appVersionService;

	@RequestMapping(value="/login")
	public String BavkendShow(){
		logger.debug("=================>hello,ManagerController!");
		return "backendlogin";
	}

	@RequestMapping(value="/login/backend/main")
	public String main(String userCode,String userPassword,Model model,HttpSession session){
		BackendUser backendUser = new BackendUser();
		backendUser = backendUserService.backendUserlogin(userCode, userPassword);
		if(backendUser == null){
			model.addAttribute("error", "用户名或密码不正确！");
			return "backendlogin";
		}else{
			session.setAttribute(Constants.USER_SESSION, backendUser);
		}
		return "backend/main";
	}

	@RequestMapping(value="/backend/app/list")
	public String Backendlist(Model model,
			@RequestParam(value="querySoftwareName",required=false )String querySoftwareName,
			@RequestParam(value="queryFlatformId",required=false )String queryFlatformId,
			@RequestParam(value="queryCategoryLevel1",required=false )String queryCategoryLevel1,
			@RequestParam(value="queryCategoryLevel2",required=false )String queryCategoryLevel2,
			@RequestParam(value="queryCategoryLevel3",required=false )String queryCategoryLevel3,
			@RequestParam(value="pageIndex",required=false ) String pageIndex,
			HttpSession session){
		List<AppInfo> AppInfoList = new ArrayList<AppInfo>();
		AppInfo app = new AppInfo();
		Integer _queryFlatformId = null;
		Integer _queryCategoryLevel1 = null;
		Integer _queryCategoryLevel2 = null;
		Integer _queryCategoryLevel3 = null;
		//设置页面容量
		int pageSize = Constants.pageSize;
		//当前页码
		int currentPageNo = 1;
		//当前用户id
		DevUser devId = (DevUser)session.getAttribute(Constants.DEVUSER_SESSION);
		if(querySoftwareName == null){
			querySoftwareName = "";
		}
		app.setSoftwareName(querySoftwareName);
		if(queryFlatformId != null && queryFlatformId != ""){
			_queryFlatformId = Integer.parseInt(queryFlatformId);
		}
		if(queryCategoryLevel1 != null && queryCategoryLevel1 != ""){
			_queryCategoryLevel1 = Integer.parseInt(queryCategoryLevel1);
		}
		if(queryCategoryLevel2 != null && queryCategoryLevel2 != ""){
			_queryCategoryLevel2 = Integer.parseInt(queryCategoryLevel2);
		}
		if(queryCategoryLevel3 != null && queryCategoryLevel3 != ""){
			_queryCategoryLevel3 = Integer.parseInt(queryCategoryLevel3);
		}
		app.setFlatformId(_queryFlatformId);
		app.setStatus(1);
		app.setCategoryLevel1(_queryCategoryLevel1);
		app.setCategoryLevel2(_queryCategoryLevel2);
		app.setCategoryLevel3(_queryCategoryLevel3);
		if(pageIndex != null){
			try {
				currentPageNo = Integer.valueOf(pageIndex);
			} catch (Exception e) {
				return "error";
			}
		}
		//总数量
		int totalCount = appInfoService.appInfoCount(app);
		//总页数
		PageSupport pages=new PageSupport();
		pages.setCurrentPageNo(currentPageNo);
		pages.setPageSize(pageSize);
		pages.setTotalCount(totalCount);

		int totalPageCount = pages.getTotalPageCount();
		//控制首页和尾页
		if(currentPageNo < 1){
			currentPageNo = 1;
		}else if(currentPageNo > totalPageCount){
			currentPageNo = totalPageCount;
		}
		app.setCurrentPageNo((currentPageNo-1)*pageSize);
		app.setPageSize(pageSize);
		AppInfoList = appInfoService.appInfoList(app);
		model.addAttribute("appInfoList", AppInfoList);
		List<DataDictionary> statusList = dataDictionaryService.getAppStatusList();
		model.addAttribute("statusList", statusList);
		List<DataDictionary> flatFormList = dataDictionaryService.getAppFlatformList();
		model.addAttribute("flatFormList", flatFormList);
		List<AppCategory> categoryLevel1List = appCategoryService.getAppCategorylsit1();
		model.addAttribute("categoryLevel1List", categoryLevel1List);
		List<AppCategory> categoryLevel2List = null;
		//二级分类列表和三级分类列表---回显
		if(queryCategoryLevel2 != null && !queryCategoryLevel2.equals("")){
			categoryLevel2List = getCategoryList(_queryCategoryLevel1.toString());
			model.addAttribute("categoryLevel2List", categoryLevel2List);
		}
		List<AppCategory> categoryLevel3List = null;
		if(queryCategoryLevel3 != null && !queryCategoryLevel3.equals("")){
			categoryLevel3List = getCategoryList(_queryCategoryLevel2.toString());
			model.addAttribute("categoryLevel3List", categoryLevel3List);
		}
		model.addAttribute("pages", pages);
		model.addAttribute("querySoftwareName", querySoftwareName);
		model.addAttribute("queryFlatformId", queryFlatformId);
		model.addAttribute("queryCategoryLevel1", queryCategoryLevel1);
		model.addAttribute("queryCategoryLevel2", queryCategoryLevel2);
		model.addAttribute("queryCategoryLevel3", queryCategoryLevel3);
		return "backend/applist";

	}
	/**
	 * 根据parentId查询出相应的分类级别列表
	 * @param pid
	 * @return
	 */
	@RequestMapping(value="/categorylevellist.json",method=RequestMethod.GET)
	@ResponseBody
	public List<AppCategory> getAppCategoryList (@RequestParam String pid){
		logger.debug("/getAppCategoryList pid ============ " + pid);
		if(pid.equals("")) pid = null;
		return getCategoryList(pid);
	}
	/**
	 * 根据parentId查询出相应的分类级别列表
	 * @param pid
	 * @return
	 */
	public List<AppCategory> getCategoryList (String pid){
		List<AppCategory> categoryLevelList = null;
		try {
			categoryLevelList = appCategoryService.getAppCategoryListByParentId(pid==null?null:Integer.parseInt(pid));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return categoryLevelList;
	}
	@RequestMapping("/datadictionarylist.json")
	@ResponseBody
	public List<DataDictionary> DataDictionaryflatFormList(){
		List<DataDictionary> flatFormList = null;
		try {
			flatFormList = dataDictionaryService.getAppFlatformList();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flatFormList;
	}

	@RequestMapping("getCategoryList1.json")
	@ResponseBody
	public List<AppCategory> getCategoryList1(){
		List<AppCategory> getCategoryList1 = null;
		try {
			getCategoryList1 = appCategoryService.getAppCategorylsit1();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return getCategoryList1;
	}
	
	@RequestMapping(value="/check")
	public String check(String aid,Model model){
		AppInfo appInfo = appInfoService.appInfoById(Integer.parseInt(aid));
		model.addAttribute(appInfo);
		AppVersion appVersion = appVersionService.appVersionById(appInfo.getVersionId());
		model.addAttribute(appVersion);
		return "backend/appcheck";
	}
	
	@RequestMapping(value="/checksave")
	public String checksave(String id,String status){
		AppInfo appInfo = new AppInfo();
		appInfo.setId(Integer.parseInt(id));
		appInfo.setStatus(Integer.parseInt(status));
		appInfo.setUpdateDate(new Date(System.currentTimeMillis()));
		if(appInfoService.appInfomodify(appInfo)){
			return "redirect:/manager/backend/app/list";
		}
		return "redirect:/manager/check";
	}
	
	@RequestMapping("/logout")
	public String logout(HttpSession session){
		session.removeAttribute(Constants.USER_SESSION);
		return "redirect:/manager/login";
	}
}
